package api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import domain.User;
import exception.RegisterException;
import service.UserService;
import utils.GetRequestJsonUtils;
import utils.Response;
import utils.ResponseCode;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.UUID;

public class RegisterServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        User user=null;
        Response build=null;
        try {
            JSONObject object = GetRequestJsonUtils.getRequestJsonObject(req);
            String user_str = object.getString("user");
            //第二步：转换参数成user对象；
             user = JSON.parseObject(user_str, User.class);
            UUID uuid = UUID.randomUUID();//生成一个随机的字符串，不会出现相同的字符串
            user.setActiveCode(uuid.toString());
        }catch (Exception e){
            e.printStackTrace();
            build=Response.build(ResponseCode.NOT_ACTIVES);
            resp.setContentType("application/json;charset=utf-8");
            resp.getWriter().write(JSON.toJSON(build).toString());
            return;
        }
        //第三步：去查询数据库中是否有这个记录
        UserService userService=new UserService();

        try {
            userService.register(user);//登陆成功，返回数据
            //创建一个sessioin,该Session对象是这个请求对应浏览器独有
            build= Response.build(ResponseCode.OK_REGISIER);
        }catch ( RegisterException e){
            e.printStackTrace();//注册异常，返回成功消息
            build= Response.build(e.getError());
        }
        //第四部：判断为空，生成登录失败的消息对象
        //第五步：把消息对象转换层字符串，返回浏览器
        resp.setContentType("application/json;charset=utf-8");
        resp.getWriter().write(JSON.toJSON(build).toString());

    }
}
